const {MongoClient,ObjectID} = require("mongodb");
const Config = require("./config");

class DB{
    //单一模型
    static getInstance(){
        if(!DB.instance){
                DB.instance = new DB()
        }
        return DB.instance;
    }
    //构造器
    constructor(){
        this.dbClient = null;
        this.connect();
    }
    //连接数据库
    connect(){
        return new Promise((resolve,reject)=>{
            //如果原本的连接不存在,那就创建一个
            if(!this.dbClient){
                MongoClient.connect(Config.dbUrl,
                    {useUnifiedTopology:true},
                    (err,client) =>{
                        if(err){
                            console.log("[Mongoose] connection close unexpectedly");
                            reject(err);
                        }else{
                            console.log('[Mongoose] connect to '+Config.dbUrl+' successfully');
                            this.dbClient = client.db(Config.dbName);
                            resolve(this.dbClient);
                        }
                    }
                )
            }else{
                //如果存在就直接获取接口
                resolve(this.dbClient);
            }
        })
    }
	
	//关闭数据库
	close(){
	    return new Promise((resolve,reject)=>{
	        if(this.dbClient){
	           MongoClient.close();
			   resolve(true);
	        }else{
	            resolve(false);
	        }
	    })
	}

    /*
    * @1:集合名字; String
    * @2:json对象; Object
    * 异步插入操作
    * 返回插入对象
    */
    insert(collection,obj){
        return new Promise((resolve,reject)=>{
            this.connect().then((db)=>{
                db.collection(collection).insertOne(obj,(err,result)=>{
                    if(!err){
                        resolve(result);
                    }else{
                        reject(err);
                    }
                })
            }).catch((err)=>{
                reject(err);
            })
        })
    }

    /*
    * @1:集合名字;String
    * @2:json对象;Object
    * 异步查找操作
    * 返回一个数组
    */
    find(collection,obj){
        return new Promise((resolve,reject)=>{
            this.connect().then((db)=>{
                var result = db.collection(collection).find(obj);
                result.toArray((err,docs)=>{
                    if(!err){
                        resolve(docs);
                    }else{
                        reject(err);
                    }
                })
            })
        })
    }

    update(collection, json1, json2) {
        return new Promise((resolve, reject) => {
            this.connect().then((db) => {
                db.collection(collection).updateOne(
                    json1,
                    {
                        $set: json2,
                    },
                    (err, result) => {
                        if (!err) {
                            resolve(result);
                        } else {
                            reject(err);
                        }
                    }
                );
            });
        });
    }

    //删除操作
    deleteItems(collection, json) {
        return new Promise((resolve, reject) => {
            this.connect().then((db) => {
                db.collection(collection).removeOne(json, (err, result) => {
                    if (!err) {
                        resolve(result);
                    } else {
                        reject(err);
                    }
                });
            });
        });
    }


    getObjectID(id){
        return new ObjectID(id);
    }

}//END CLASS

module.exports = DB.getInstance();